package view.pane;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import controller.human.Person;
import controller.human.User;

import view.Gui;

@SuppressWarnings("serial")
public class EnlistmentPane extends JPanel {
	Gui gui;
	
	public EnlistmentPane(Gui guiParam) {
		this.gui = guiParam;
		Set<User> users = gui.getUsers();
		
		JPanel existingUsers = new JPanel(); 
		existingUsers.setLayout(new GridLayout(users.size(),2));
		
		for (User user: users) {
			JLabel userName = new JLabel(user.getName());
			JButton delete = new JButton();
			
			delete.addActionListener(new DeleteActionListener(user));
			
			existingUsers.add(userName);
			existingUsers.add(delete);
		}
		this.setLayout(new GridLayout(3,1));
		this.add(existingUsers);
		
		JPanel addNewUser = new JPanel();
		addNewUser.setLayout(new GridLayout(1,3));
		
		final JTextField userName = new JTextField("name", 10);
		final JPasswordField userPass = new JPasswordField("pass", 10);
		JButton addButton = new JButton("Add");
		addNewUser.add(userName);
		addNewUser.add(userPass);
		addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				User user = Person.getUser(userName.getText());
				user.setPassword((userPass.getText()));
				gui.addUser(user);
				gui.updatePane(new EnlistmentPane(gui));
			}
		});
		addNewUser.add(addButton);
		this.add(addNewUser);
		
		JButton done = new JButton("Done");
		done.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO move start new session on new botton on some screen
				gui.startNewSession();
				gui.updatePane(new MainPane(gui));
			}
		});
		this.add(done);
	}
	
	private class DeleteActionListener implements ActionListener {
		User user;
		DeleteActionListener(User user) {
			this.user = user;
		}
		
		public void actionPerformed(ActionEvent e) {
			System.out.println("Deleting user " + user.getName());
			gui.removeUser(user);
			gui.updatePane(new EnlistmentPane(gui));
		}
		
	}	
}
